"""
RedFire Trading Service - 重构版本
=================================
使用RedFireServiceBase重构的交易服务
"""

import logging

# 统一路径管理
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../..'))

# 中心化配置系统
from redfire_framework import RedFireContainer, RedFireSettings
from redfire_framework.core.database import DatabaseManager
from redfire_framework.logging.manager import configure_logging
from .api.trading_routes import router as trading_router
from .services.trading_service import TradingService
from redfire_framework.cache.backends import RedisCache as RedisManager
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi.middleware.cors import CORSMiddleware

# 全局日志记录器
logger = logging.getLogger(__name__)

# 全局数据库管理器实例
db_manager: UnifiedDatabaseManager = UnifiedDatabaseManager()

# 全局Redis管理器实例
redis_manager: RedisManager = RedisManager()

# 全局服务实例
# 在应用启动时进行初始化
trading_service_instance: TradingService = None


class TradingServiceApp(RedFireAPIServiceBase):
    """交易服务"""
    
    def __init__(self):
        # 1. 在初始化父类之前配置日志
        setup_logging()
        
        # 2. 加载并验证中心化配置
        self.service_config = ConfigManager().get_service_config("trading-service")
        
        # 验证配置的正确性
        validation_errors = ConfigManager().validate_all_configs()
        if validation_errors:
            error_msg = f"配置验证失败: {', '.join(validation_errors)}"
            logger.critical(error_msg)
            raise ValueError(error_msg)
        
        super().__init__("trading-service", self.service_config)
    
    async def on_startup(self):
        """启动时初始化"""
        await super().on_startup()
        
        # 3. 初始化Redis连接
        try:
            redis_config = self.service_config.get("redis")
            if not redis_config:
                logger.critical("未在中心化配置中找到Redis配置")
                raise ValueError("未在中心化配置中找到Redis配置")
            
            await redis_manager.initialize(redis_config)
            self.logger.info("✅ Redis连接已通过 RedisManager 建立")
        except Exception as e:
            self.logger.critical(f"❌ Redis初始化失败: {e}", exc_info=True)
            raise

        # 4. 初始化数据库连接 - 使用新的中心化数据库配置系统
        try:
            from shared.data.db_config import load_all_databases, register_all_databases
            
            # 加载标准化数据库配置
            db_config = load_all_databases("trading-service", self.service_config)
            self.logger.info(f"✅ 已加载 {len(db_config.databases)} 个数据库配置")
            
            # 注册所有数据库到管理器
            global db_manager
            db_manager = await register_all_databases("trading-service", db_config, db_manager)
            await db_manager.initialize()
            
            self.logger.info("✅ 数据库连接已通过中心化配置系统建立")
        except Exception as e:
            self.logger.error(f"❌ 新数据库配置系统失败: {e}")
            raise

        # 5. 初始化服务实例
        global trading_service_instance
        trading_service_instance = TradingService(redis_client=redis_manager.get_client())
        self.logger.info("✅ TradingService 实例已创建")
    
    async def on_shutdown(self):
        """关闭时清理"""
        # 6. 清理数据库连接
        try:
            await db_manager.cleanup()
            self.logger.info("✅ 数据库连接已通过 UnifiedDatabaseManager 关闭")
        except Exception as e:
            self.logger.error(f"❌ 数据库关闭失败: {e}", exc_info=True)
            
        # 7. 清理Redis连接
        try:
            await redis_manager.cleanup()
            self.logger.info("✅ Redis连接已通过 RedisManager 关闭")
        except Exception as e:
            self.logger.error(f"❌ Redis关闭失败: {e}", exc_info=True)
        
        await super().on_shutdown()
    
    def setup_routes(self):
        """设置路由"""
        if not self.app:
            return
            
        # 根路径
        @self.app.get("/")
        async def root():
            """根路径信息"""
            return {
                "service": "RedFire 交易服务",
                "version": self.version,
                "description": "RedFire量化交易平台核心交易服务",
                "status": "running",
                "health_check": f"{self.app.root_path}/health",
                "api_docs": [
                    f"{self.app.root_path}/docs",
                    f"{self.app.root_path}/redoc"
                ]
            }
        
        # 包含交易相关的路由
        self.app.include_router(trading_router)
    
    async def get_health_status(self) -> dict:
        """
        获取当前服务的健康状态.
        覆盖基类方法以添加数据库健康检查.
        """
        # 8. 检查数据库连接状态
        db_health_results = await db_manager.health_check()
        
        # 我们关心主数据库是否健康
        primary_db_health = db_health_results.get("mysql_trading", {})
        is_db_healthy = primary_db_health.get("healthy", False)

        # 9. 检查Redis连接状态
        redis_health = await redis_manager.health_check()
        is_redis_healthy = redis_health.get("healthy", False)
        
        # 合并基础健康状态和数据库状态
        health_status = await super().get_health_status()
        health_status['healthy'] = health_status['healthy'] and is_db_healthy and is_redis_healthy
        health_status['dependencies']['database'] = {
            "status": "healthy" if is_db_healthy else "unhealthy",
            "details": primary_db_health
        }
        health_status['dependencies']['redis'] = redis_health
        return health_status


# 创建服务实例
service = TradingServiceApp()

# 获取应用实例，以便 uvicorn 等服务器可以发现它
app = service.get_app()

# ==================== Dependency Injection Providers ====================

async def get_db_session() -> AsyncSession:
    """
    FastAPI 依赖项，用于获取数据库会话。
    它从主数据库连接中获取一个会话，并在请求完成后自动关闭它。
    """
    async with db_manager.get_primary_session() as session:
        yield session

def get_trading_service() -> TradingService:
    """
    FastAPI 依赖项，用于获取 TradingService 的单例。
    """
    if trading_service_instance is None:
        raise RuntimeError("TradingService尚未初始化。应用是否已完全启动？")
    return trading_service_instance


if __name__ == "__main__":
    # 10. 使用配置中的端口和主机启动服务
    host = service.service_config.get('host', '0.0.0.0')
    port = service.service_config.get('port', 8003)
    
    logger.info(f"🚀 准备以独立模式启动交易服务于 http://{host}:{port}")
    service.run()